package net.gitosc.lianqu1990.common.util;

import net.gitosc.lianqu1990.common.enums.ResponseState;
import net.gitosc.lianqu1990.common.ResponseData;
import org.springframework.cglib.beans.ImmutableBean;

/**
 * @author hanchao
 * @date 2017年4月13日 下午4:54:47
 */
public class ResponseUtil {
    /**
     * 为了方便返回
     */
    public static final ResponseData SUCCESS = createImmutableResponse(createResponse(ResponseState.SUCCESS));
    public static final ResponseData FAILED = createImmutableResponse(createResponse(ResponseState.FAILED));
    public static final ResponseData BAD_REQUEST = createImmutableResponse(createResponse(ResponseState.BAD_REQUEST));
    public static final ResponseData UNAUTHORIZED = createImmutableResponse(createResponse(ResponseState.UNAUTHORIZED));
    public static final ResponseData FORBIDDEN = createImmutableResponse(createResponse(ResponseState.FORBIDDEN));
    public static final ResponseData NOT_FOUND = createImmutableResponse(createResponse(ResponseState.NOT_FOUND));
    public static final ResponseData SERVER_ERROR = createImmutableResponse(createResponse(ResponseState.SERVER_ERROR));

    /**
     * 创建一个带data的response，如果传入的response是自己生成的，不建议使用。在response为提前创建好的不可变下使用
     * 在responsestate之外的返回同时需要携带data场景比较少，该方法建议最少调用
     * @param data
     * @return
     */
    public static <T> ResponseData<T> createResponse(ResponseData response,T data){
        return createResponse(response.getCode(),response.getMessage()).setData(data);
    }

    /**
     * 用枚举创建一个response
     * @param code
     * @return
     */
    public static ResponseData createResponse(ResponseState state){
        return new ResponseData(state.getCode(),state.getMessage());
    }

    /**
     * 用code&message创建一个response
     * @param code
     * @param message
     * @return
     */
    public static ResponseData createResponse(int code,String message){
        return new ResponseData(code,message);
    }

    /**
     * 创建不可变的response
     * @param data
     * @return
     */
    public static ResponseData createImmutableResponse(ResponseData data){
        return (ResponseData) ImmutableBean.create(data);
    }

    /**
     * 创建不可变的response
     * @param code
     * @param message
     * @return
     */
    public static ResponseData createImmutableResponse(int code,String message){
        return createImmutableResponse(createResponse(code,message));
    }

    /**
     * 创建不可变的response
     * @param state
     * @return
     */
    public static ResponseData createImmutableResponse(ResponseState state){
        return createImmutableResponse(createResponse(state));
    }

}
